package com.cloud.wms.ui.inside.fragment;

import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.widget.decoration.LinearVerticalDecoration;
import com.cloud.widget.EditTextDel;
import com.cloud.widget.ScanText;
import com.cloud.widget.expand.ExpandLayout;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.widget.utils.KeyBoardUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.ui.common.activity.SelectBatchActivity;
import com.cloud.wms.ui.inside.contract.ReplenishUpContract;
import com.cloud.wms.ui.inside.entity.ReplenishBindEntity;
import com.cloud.wms.ui.inside.entity.ReplenishCommodityEntity;
import com.cloud.wms.ui.inside.presenter.ReplenishUpPresenter;
import com.cloud.wms.ui.inside.replenish.ReplenishDownActivity;
import com.cloud.wms.ui.main.entity.BatchEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.widget.dialog.TaskCompleteDialog;
import com.trello.rxlifecycle3.LifecycleTransformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-03-07 16:10
 * @Description:
 */
public class ReplenishUpFragment extends BaseViewPagerFragment<ReplenishUpPresenter> implements ReplenishUpContract.View {
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.tv_commodity_code)
    TextView tvCommodityCode;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.et_commodity_amount)
    EditText etCommodityAmount;
    @BindView(R.id.tv_order_commodity_amount)
    TextView tvOrderCommodityAmount;
    @BindView(R.id.tv_commodity_shelf_amount)
    TextView tvCommodityShelfAmount;
    @BindView(R.id.tv_recommend_pos)
    TextView tvRecommendPos;
    @BindView(R.id.et_shelf_pos)
    EditTextDel etShelfPos;
    @BindView(R.id.iv_toggle_batch)
    ImageView ivToggleBatch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.expand_layout)
    ExpandLayout expandLayout;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.iv_select_batch)
    AppCompatImageView ivSelectBatch;
    @BindView(R.id.tv_batch_amount)
    TextView tvBatchAmount;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String amountStr = s.toString();
            if (s.length() > 1 && s.toString().startsWith("0")) {
                amountStr = s.toString().replaceFirst("0", "");
                etCommodityAmount.setText(amountStr);
            }
            verifyRequired();
        }
    };
    private ReplenishCommodityEntity commodityEntity;
    private BaseQuickAdapter<BatchEntity, BaseViewHolder> mBatchAdapter;
    private TaskEntity taskEntity;
    private ReplenishBindEntity bindInfoEntity;

    @Override
    protected int getResId() {
        return R.layout.fragment_inside_replenish_up;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        taskEntity = getArguments().getParcelable("Task");
        bindInfoEntity = getArguments().getParcelable("OrderInfoEntity");
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvList.setLayoutManager(manager);
        mBatchAdapter = new BaseQuickAdapter<BatchEntity, BaseViewHolder>(R.layout.item_common_select_batch) {
            @Override
            protected void convert(BaseViewHolder helper, BatchEntity item) {
                helper.setText(R.id.tv_produce_date, item.getProductionDate())
                        .setText(R.id.tv_deadline_date, item.getExpirationDate())
                        .setText(R.id.tv_in_date, item.getInDate());
            }
        };
        rvList.setItemAnimator(new DefaultItemAnimator());
        rvList.addItemDecoration(new LinearVerticalDecoration(DensityUtils.Dp2Px(getContext(), 10)));
        rvList.setAdapter(mBatchAdapter);

        etShelfPos.setOnKeyListener(onKeyListenerImp);
        btnSubmit.setEnabled(false);
        etShelfPos.addTextChangedListener(textWatcher);
        etCommodityAmount.addTextChangedListener(textWatcher);

        expandLayout.setOnExpansionUpdateListener((expansionFraction, state) -> {
            ivToggleBatch.setRotation(expansionFraction * 90);
        });

        mPresenter.loadReplenishCommodity(taskEntity.getBillID());
    }

    @Override
    public ScanText getScanText() {
        return scanText;
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        if (etShelfPos.isFocused()) {
            if (result.equalsIgnoreCase(commodityEntity.getDestPosCode())) {
                etShelfPos.setText(result);
                etShelfPos.setSelection(result.length());
                success("库位扫描验证成功！");

                verifyRequired();

                KeyBoardUtils.hideKeyBoard(etShelfPos, getContext());
                etCommodityAmount.requestFocus();
            } else {
                info("库位扫描验证失败！");
            }
        } else {
            scanText.addHistory(result);
            if (commodityEntity.matchBarCode(result)) {
                tvCommodityCode.setTag(true);
                success("商品扫描验证成功！");
                etShelfPos.requestFocus();
                verifyRequired();
                KeyBoardUtils.hideKeyBoard(scanText, getContext());
            } else {
                info("商品扫描验证失败！");
            }
        }
    }

    @Override
    protected void initData() {

    }

    private void verifyRequired() {
        Object tag = tvCommodityCode.getTag();
        if (tag == null || !((boolean) tag)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String shelfPos = etShelfPos.getText().toString().trim();
        if (TextUtils.isEmpty(shelfPos) || commodityEntity == null || !shelfPos.equalsIgnoreCase(commodityEntity.getDestPosCode())) {
            btnSubmit.setEnabled(false);
            return;
        }
        if (mBatchAdapter.getData().isEmpty()) {
            btnSubmit.setEnabled(false);
            return;
        }
        String commodityAmount = etCommodityAmount.getText().toString().trim();
        if (TextUtils.isEmpty(commodityAmount)) {
            btnSubmit.setEnabled(false);
            return;
        }
        btnSubmit.setEnabled(true);
    }

    private boolean verifySubmit() {
        if (commodityEntity == null) {
            info("请先扫描商品");
            return false;
        }
        Object tag = tvCommodityCode.getTag();
        if (tag == null || !((boolean) tag)) {
            info("请扫描商品！");
            return false;
        }
        String shelfPos = etShelfPos.getText().toString().trim();
        if (TextUtils.isEmpty(shelfPos)) {
            info("请扫描商品上架库位");
            return false;
        }
        if (TextUtils.isEmpty(shelfPos) || !shelfPos.equalsIgnoreCase(commodityEntity.getDestPosCode())) {
            info("请按提示扫描库位");
            return false;
        }
        if (mBatchAdapter.getData().isEmpty()) {
            info("请先选择商品批次");
            return false;
        }
        String commodityAmount = etCommodityAmount.getText().toString().trim();
        if (TextUtils.isEmpty(commodityAmount)) {
            info("上架数量为必填项");
            return false;
        }
        if (!NumberUtils.isInt(commodityAmount) || NumberUtils.getIntegerValue(commodityAmount) <= 0) {
            info("上架数量必须为整数且必须大于0");
            return false;
        }

        int sum = 0;
        for (int i = 0; i < mBatchAdapter.getData().size(); i++) {
            sum += mBatchAdapter.getData().get(i).getAmount();
        }
        if (NumberUtils.getIntegerValue(commodityAmount) > sum) {
            info("上架数量必须小于应上架数量:" + sum);
            return false;
        }
        commodityEntity.setAmount(NumberUtils.getIntegerValue(commodityAmount));
        return true;
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case ReplenishUpPresenter.REPLENISH_COMMODITY:
                commodityEntity = (ReplenishCommodityEntity) message.obj;
                tvCommodityName.setText(commodityEntity.getCommodityName());
                tvCommodityCode.setText(commodityEntity.getBarCode());
                tvRecommendPos.setText(commodityEntity.getDestPosCode());
                tvCommodityCode.setTag(false);
                tvOrderCommodityAmount.setText(commodityEntity.getFactDownAmount() - commodityEntity.getFactUpAmount() + "");
                tvCommodityShelfAmount.setText(commodityEntity.getFactUpAmount() + "");
                etCommodityAmount.setText("");

                if (commodityEntity.getDownBatchList().size() == 1) {
                    ivSelectBatch.setVisibility(View.GONE);
                } else {
                    ivSelectBatch.setVisibility(View.VISIBLE);
                }
                setBatchToList(commodityEntity.getDownBatchList());

                commodityEntity.setUpBatchList(commodityEntity.getDownBatchList());
                scanText.getFocus();
                break;
            case ReplenishUpPresenter.REPLENISH_UP:
                resetView();
                break;
            case ReplenishUpPresenter.REPLENISH_COMPLETE:
                new TaskCompleteDialog(getActivity()).show();
                break;
            case ReplenishUpPresenter.REPLENISH_UP_COMPLETE:
                TaskCompleteDialog dialog = new TaskCompleteDialog(getActivity());
                dialog.show();
                dialog.setOnNextListener(
                        () -> {
                            ReplenishDownActivity.start(getContext(), bindInfoEntity, taskEntity);
                            getActivity().finish();
                            dialog.dismiss();
                        },
                        "立即去下架");
                break;
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventCome(Event event) {
        if (event == null) {
            return;
        }
        switch (event.getCode()) {
            case EventConfig.SELECT_BATCH:
                ArrayList<BatchEntity> batchEntities = (ArrayList<BatchEntity>) event.getData();
                setBatchToList(batchEntities);
                success("批次选择成功！");
                verifyRequired();
                break;
        }
    }

    private void setBatchToList(List<BatchEntity> batchEntities) {
        mBatchAdapter.setNewInstance(batchEntities);
        int sum = 0;
        for (int i = 0; i < batchEntities.size(); i++) {
            sum += batchEntities.get(i).getAmount();
        }
        commodityEntity.setUpBatchList(batchEntities);
        etCommodityAmount.setText(sum + "");
        tvBatchAmount.setVisibility(View.VISIBLE);
        tvBatchAmount.setText(MessageFormat.format("可上架数量：{0}", sum));
    }


    @OnClick({R.id.btn_submit, R.id.iv_select_batch, R.id.iv_toggle_batch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_select_batch:
                if (commodityEntity.getDownBatchList().size() == 1) {
                    info("当前库位商品只有一个批次，无需选择！");
                    return;
                }
                SelectBatchActivity.start(getContext(), (ArrayList<BatchEntity>) commodityEntity.getDownBatchList(), false);
                break;
            case R.id.iv_toggle_batch:
                expandLayout.toggle(true);
                break;
            case R.id.btn_submit:
                if (verifySubmit()) {
                    String commodityAmount = etCommodityAmount.getText().toString().trim();
                    mPresenter.confirmReplenishUp(taskEntity,
                            bindInfoEntity,
                            commodityEntity,
                            NumberUtils.getIntegerValue(commodityAmount),
                            mBatchAdapter.getData());
                }
                break;
        }
    }

    /**
     * 重置页面
     */
    private void resetView() {
        mBatchAdapter.getData().clear();
        mBatchAdapter.notifyDataSetChanged();
        expandLayout.collapse();
        commodityEntity = null;
        btnSubmit.setEnabled(false);
        tvCommodityCode.setText("");
        tvCommodityName.setText("");
        etCommodityAmount.setText("");
        etShelfPos.setText("");
        tvOrderCommodityAmount.setText("");
        tvCommodityShelfAmount.setText("");
        nestedScrollView.smoothScrollTo(0, 0);
        scanText.requestFocus();

        mPresenter.loadReplenishCommodity(taskEntity.getBillID());
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    public static BaseViewPagerFragment newInstance(Bundle bundle) {
        ReplenishUpFragment fragment = new ReplenishUpFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
}
